package org.six11.ss.server;

import java.util.TimerTask;

import org.hibernate.FlushMode;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 * A simple subclass of TimerTask that lets you make delayed actions in a hibernate-safe way.
 * Instead of implementing the 'run' function, implement 'go', and it will run safely.
 * 
 * @author Gabe Johnson <johnsogg@cmu.edu>
 */
public abstract class HiberTask extends TimerTask {

  private SessionFactory sessionFactory;

  public HiberTask(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
  }

  /**
   * 
   */
  @Override
  public void run() {
    sessionFactory.getCurrentSession().setFlushMode(FlushMode.ALWAYS);
    Transaction tx = sessionFactory.getCurrentSession().beginTransaction();
    try {
      go();
    } finally {
      tx.commit();
    }
  }

  public abstract void go();

}
